﻿using System;
using System.IO;

namespace MediaController.Utils.Listener
{
    public abstract class WatchAdapter : IDisposable
    {
        protected FolderListener _folderListeners;
        private readonly string _path;

        public string Filter { get; set; }

        protected WatchAdapter(string path)
        {
            _path = path;
        }

        public virtual void Start()
        {
            Start(_path);
        }

        /// <summary>
        /// Start watching for file in the given folder
        /// </summary>
        /// <param name="path">path to listen for new files</param>
        public void Start(string path)
        {
            if (path == null) throw new ArgumentNullException("path");

            if (!Directory.Exists(path)) throw new DirectoryNotFoundException();

            if (_folderListeners != null && _folderListeners.Enabled) throw new Exception("Cannot start listening while watching other.");


            string directoryName = Path.GetFullPath(path);
            _folderListeners = new FolderListener(directoryName, Filter, 4);
            _folderListeners.FileReceived += OnFolderListenerFileReceived;
            _folderListeners.StartAsync();
        }

        /// <summary>
        /// Stop watching the folder
        /// </summary>
        public void Stop()
        {
            _folderListeners.Stop();
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            _folderListeners.Dispose();
        }

        /// <summary>
        /// Haendel new file that recived from the watching folder
        /// </summary>
        /// <param name="folderListener"></param>
        /// <param name="receivedFileInfo"></param>
        protected abstract void OnFolderListenerFileReceived(FolderListener folderListener, ReceivedFileInfo receivedFileInfo);

    }
}
